import Vue from 'vue'
/**
 * ①添
 * @@新增 定义初始化菜单
 */
// import axios from 'axios'
import { getToken, localSave, localRead } from '@/libs/util'
// import config from '@/config'
import { lazyLoadingCop } from '@/libs/tools'
import { getMockMenuData } from '@/api/data'
import Main from '@/components/main' // Main 是架构组件，不在后台返回，在文件里单独引入
import parentView from '@/components/parent-view' // 获取组件的方法
import store from '@/store' // parentView 是二级架构组件，不在后台返回，在文件里单独引入
import {getMenuData} from '@/api/menu'
import * as ResponseStatus from '@/api/response-status'
// eslint-disable-next-line no-unused-vars
import config from '../config'

const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.devServer : config.baseUrl.proServer


var gotRouter
// 初始化路由
export const initRouter = (self) => {
  console.log('开始初始化路由')
  if (!getToken()) {
    console.log('没有获取到token')
    return
  }
  var routerData
  gotRouter = dynamicRouterAdd(self)
  return gotRouter
}

/**
 * 过滤菜单数据，返回菜单需要的数据
 * @param {*} row 
 */
export const filterMenuData = (rows) => {
  // 获取到所有一级菜单
  let oneLevelMenuArr = rows.filter((item) => {
    return item.sysMenuMenuLevel === 1
  })
  // 获取到所有二级菜单
  let twoLevelmenuArr = rows.filter((item) => {
    return item.sysMenuMenuLevel === 2
  })
  // 获取到所有三级菜单
  let threeLevelmenuArr = rows.filter((item) => {
    return item.sysMenuMenuLevel === 3
  })
  // 定义菜单数组
  let menuDataArr = []
  // 循环一级菜单
  oneLevelMenuArr.forEach(oneLevel => {
    const oneMenuData = encapsulationData(oneLevel)
    let twoChildren = []
    let oneMenuId = oneLevel.sysMenuId
    // 循环二级菜单
    twoLevelmenuArr.forEach(twoLevel => {
      if (oneMenuId === twoLevel.sysMenuParentId) {
        const twoMenuData = encapsulationData(twoLevel)
        let threeChildren = []
        let twoMenuId = twoLevel.sysMenuId
        // 循环三级菜单
        threeLevelmenuArr.forEach(threeLevel => {
          if (twoMenuId === threeLevel.sysMenuParentId) {
            const threeMenuData = encapsulationData(threeLevel)
            threeChildren.push(threeMenuData)
          }
        })
        twoMenuData.children = threeChildren
        twoChildren.push(twoMenuData)
      }
    })
    oneMenuData.children = twoChildren
    menuDataArr.push(oneMenuData)
  })
  return menuDataArr
}

/**
 * 根据菜单数据封装成需要的菜单数据
 * @param {}} level 
 */
export const encapsulationData = (level) => {
  let menuData = {}
  menuData.path = level.sysMenuPath
  menuData.name = level.sysMenuName
  if (level.sysMenuComponent !== 'null') {
    menuData.component = level.sysMenuComponent + ''
  }
  if (level.redirect) {
    menuData.redirect = level.redirect
  }
  const meta = {}
  meta.icon = level.sysMenuMetaIcon
  meta.title = level.sysMenuMetaTitle
  if (level.sysMenuMetaHref) {
    meta.href = baseUrl + level.sysMenuMetaHref
  }
  if (level.sysMenuMetaHideInBread) {
    meta.hideInBread = level.sysMenuMetaHideInBread === 1
  }
  if (level.sysMenuMetaHideInMenu) {
    meta.hideInMenu = level.sysMenuMetaHideInMenu === 1
  }
  if (level.sysMenuMetaNotCache) {
    meta.notCache = level.sysMenuMetaNotCache === 1
  }
  if (level.sysMenuMetaAccess) {
    meta.access = level.sysMenuMetaAccess.split(',')
  }
  if (level.sysMenuMetaBeforeCloseName) {
    meta.beforeCloseName = level.sysMenuMetaBeforeCloseName
  }
  menuData.meta = meta
  return menuData
}

// 加载路由菜单,从localStorage拿到路由,在创建路由时使用
export const dynamicRouterAdd = (self) => {
  let dynamicRouter = []
  let data = localRead('dynamicRouter')
  // console.log('从本地加载出来', data)
  if (!data) {
    //  异步请求
    getMenuData().then(res => {
      if (ResponseStatus.OK === res.data.code) {
        var menuData = res.data.data;
        menuData = filterMenuData(menuData)
        // console.log('保存到本地', menuData)
        localSave('dynamicRouter', JSON.stringify(menuData));
        dynamicRouter = filterAsyncRouter(menuData);
        store.commit('updateMenuList', dynamicRouter);
      } else {
        console.log(res.data.message)
      }
    }).catch(err => {
      console.log(err)
    })
    if (dynamicRouter) {
      return dynamicRouter
    } else {
      // 异步请求到数据，初始化好数据，重新调用，冲本地储存里面调用
      dynamicRouterAdd(self)
    }
  } else {
    dynamicRouter = filterAsyncRouter(JSON.parse(data))
    return dynamicRouter
  }
  
}

// @函数: 遍历后台传来的路由字符串，转换为组件对象
export const filterAsyncRouter = asyncRouterMap => {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Main') {
        // Main组件特殊处理
        route.component = Main
      } else if (route.component === 'parentView') {
        // parentView组件特殊处理
        route.component = parentView
      } else {
        // route.component = _import(route.component)
        // route.component = lazyLoadingCop(route.component)
        const path = 'view/' + route.component + '.vue'
        route.component = () => import(`@/${path}`)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}